package utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

/**
 * Event and logging class implements the Singleton pattern and writes event
 * data to the log file EventLog.txt or ErrorLog.txt
 * 
 * @author Andrew Stokes
 */
public class Logger {

	private static Logger logger;
	public static final String EVENT = "Event";
	public static final String ERROR = "Error";
	private static final String CR_LF = "\r\n";

	private Logger() {

	}

	/**
	 * @return the single instance of the Logger class
	 */
	public static Logger getLogger() {

		// check to see if static variable logger (an object of the Logger
		// class) has been instantiated
		if (logger == null) {
			// if not create a lock on the Logger class
			synchronized (Logger.class) {
				// check again to see if the variable logger is null
				if (logger == null) {
					// instantiate the Logger class
					logger = new Logger();
				}
			}

		}
		return logger;
	}

	/**
	 * 
	 * @param logData
	 *            - String containing Event data to be written to the specific
	 *            log file specified by the parameter logClass
	 */
	public void appendLog(String logClass, String logData) {
		File file = null;
		// open the file for the specified class of log (Error or Event)
		if (logClass.equals(EVENT)) {
			file = new File("EventLog.txt");
		} else if (logClass.equals(ERROR)) {
			file = new File("ErrorLog.txt");
		}

		try {
			// append the message to the file
			FileWriter fw = new FileWriter(file, true);
			PrintWriter pw = new PrintWriter(fw);
			Calendar cal = Calendar.getInstance();

			String event = (logClass + " logged at: " + cal.getTime() + CR_LF);
			event += (logData + CR_LF);
			event += (CR_LF);
			pw.print(event);
			fw.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void clearLog(String logClass) {
		// clear the selected log file

		File file = null;
		// select/create the file for the specified class of log (Error or
		// Event)
		if (logClass.equals(EVENT)) {

			file = new File("EventLog.txt");
		} else if (logClass.equals(ERROR)) {
			file = new File("ErrorLog.txt");
		}
		try {
			// write an empty string to the file to clear any existing records
			PrintWriter pw = new PrintWriter(file);
			pw.print("");
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
